/***
 *   @title qz
 *   @description <description class purpose>
 *   @author yichen
 *   @version 1.0.0
 *   @create 2023/9/19 0019
 **/
package io.gitee.wokaixin.yunque.driver;
import io.lettuce.core.*;
import io.lettuce.core.api.*;
import io.lettuce.core.api.sync.*;

import java.time.*;
import java.time.temporal.*;

@SuppressWarnings("unchecked")
//@Service
public class RedisDriver implements Driver {
    private RedisClient CLIENT;
    private StatefulRedisConnection<String, byte[]> CONNECTION;
    private RedisURI redisUri;
    protected RedisConfig redisConfig;

//    public static RedisDriver RedisDriver(RedisConfig redisConfig) {
//        RedisDriver redisDriver =new RedisDriver(redisConfig);
//        redisDriver.redisConfig = redisConfig;
//        return redisDriver;
//    }
    public  RedisDriver(RedisConfig redisConfig) {
        this.redisConfig = redisConfig;
        createConnect(this.getRedisUri());
    }
    private RedisURI getRedisUri() {
        RedisURI redisUri = RedisURI.builder()
                .withHost(redisConfig.getHost())
                .withPort(redisConfig.getPort())
                .withDatabase(redisConfig.getDb())
                .withAuthentication(redisConfig.getUsername(), redisConfig.getPassword())
                .withTimeout(Duration.of(redisConfig.getTimeout(), ChronoUnit.SECONDS))
                .build();
        return redisUri;
    }

    public void createConnect(RedisURI redisUri) {

        CLIENT = RedisClient.create(redisUri);
        CONNECTION = CLIENT.connect(new StringByteArrayCodec(), redisUri);
        this.redisUri = redisUri;
    }

    public void close() throws Exception {
        CONNECTION.close();
        CLIENT.shutdown();
    }

    private String channelName;

    public void setChannelName(String channelName) {
        this.channelName = channelName;
    }

    public RedisDriver(RedisClient client) {
        CLIENT = client;
        CONNECTION = CLIENT.connect(new StringByteArrayCodec());
    }

    public RedisDriver(RedisURI redisUri) {
        createConnect(redisUri);
    }

    @Override
    public boolean sendTo(byte[] msg) {

        return sendTo(msg, this.channelName);
    }

    /***
     *   @author: yichen
     *   @Date: 2023/9/19 0019
     *   @Description: 发布订阅
     *   @param
     **/
    @Override
    public boolean sendTo(byte[] msg, String channel) {// <3> 创建线程安全的连接
//        RedisCommands<String, Object> redisCommands = CONNECTION.sync();                // <4> 创建同步命令
        RedisCommands<String, byte[]> commands = CONNECTION.sync();
        Long result = commands.publish(channel, msg);
        return result > 0;
    }

}
